<?php

namespace Org\SueCrypt;

/**
 * SueDes 类
 *
 * @since VER:1.0; DATE:2016-4-26; AUTHOR:SoChishun; EMAIL:14507247@qq.com; DESC:Added.
 */
class SueDes {

    // ==DES==
    /**
     * 加密
     * @param string $str 要处理的字符串
     * @param string $key 密钥,必须为8位
     * @return string 字符串可能包含+=/字符
     */
    public static function encrypt($str, $key = 'Sue123!@#') {
        $size = mcrypt_get_block_size(MCRYPT_DES, MCRYPT_MODE_CBC);
        $str = self::pkcs5Pad($str, $size);
        $aaa = mcrypt_cbc(MCRYPT_DES, $key, $str, MCRYPT_ENCRYPT, $key);
        $ret = base64_encode($aaa);
        return $ret;
    }

    /**
     * 解密
     * @param string $str 要处理的字符串
     * @param string $key 密钥,必须为8位
     * @return string
     */
    public static function decrypt($str, $key = 'Sue123!@#') {
        $strBin = base64_decode($str);
        $str = mcrypt_cbc(MCRYPT_DES, $key, $strBin, MCRYPT_DECRYPT, $key);
        $str = self::pkcs5Unpad($str);
        return $str;
    }

    private static function pkcs5Pad($text, $blocksize) {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }

    private static function pkcs5Unpad($text) {
        $pad = ord($text {strlen($text) - 1});
        if ($pad > strlen($text))
            return false;

        if (strspn($text, chr($pad), strlen($text) - $pad) != $pad)
            return false;

        return substr($text, 0, - 1 * $pad);
    }

    // ==/DES==
}
